#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <fcntl.h>

void SetNonBlock(int fd)
{
    int fl = fcntl(fd,F_GETFL);
    if(fl < 0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd,F_SETFL,fl | O_NONBLOCK); // O_NONBLOCK让fd，非阻塞模式
}

int main()
{
    std::string tips = "Please Enter# ";
    char buffer[1024];
    SetNonBlock(0);
    while(true)
    {
        write(0, tips.c_str(), tips.size());

        int n = read(0, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = '\0';
            std::cout << "echo: " << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "read file end" << std::endl;  
            break;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "底层数据，没有就绪" << std::endl; 
                sleep(1);
                continue;
            }
            else if(errno == EINTR)
            {
                std::cout << "信号中断" << std::endl;
                sleep(1);
                continue;
            }
            else
            {
                perror("read");
            }
        }
        sleep(1);
    }
    return 0;
}